import { HttpException, Injectable, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { CreateUserDto } from './dto/create-user.dto';
import { UserListDto } from './dto/user-list.dto';
import { WechatUserInfo } from '../auth/interface/auth.interface';
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}

  /**
   * 账号密码注册
   * @param createUser
   */
  async register(createUser: CreateUserDto) {
    const { username } = createUser;

    const user = await this.userRepository.findOne({
      where: { username },
    });
    if (user) {
      throw new HttpException('用户名已存在', HttpStatus.BAD_REQUEST);
    }

    const newUser = await this.userRepository.create(createUser);
    return await this.userRepository.save(newUser);
  }

  /**
   * 扫微信码注册
   * @param userInfo
   */
  async registerByWechat(userInfo: WechatUserInfo) {
    const { nickname, openid, headimgurl } = userInfo;
    const newUser = await this.userRepository.create({
      nickname,
      openid,
      avatar: headimgurl,
    });
    return await this.userRepository.save(newUser);
  }

  /**
   * 扫微信码注册
   * @param userInfo
   */
  async findByOpenid(openid: string) {
    return await this.userRepository.findOne({ where: { openid } });
  }

  async findAll(query: UserListDto) {
    const qb = await this.userRepository.createQueryBuilder('user');
    qb.orderBy('user.create_time', 'DESC');

    const count = await qb.getCount();
    const { pageNum = 1, pageSize = 10, ...params } = query;
    qb.limit(pageSize);
    qb.offset(pageSize * (pageNum - 1));

    const users = await qb.getMany();
    return { list: users, count: count };
  }

  async findOne(id: string) {
    return await this.userRepository.findOne({ where: { id } });
  }

  async update(id: string, body: CreateUserDto) {
    const existUser = await this.findOne(id);

    if (!existUser) {
      throw new HttpException(`id为${id}的用户不存在`, HttpStatus.BAD_REQUEST);
    }
    existUser.updateTime = new Date();
    const updateUser = this.userRepository.merge(existUser, body);
    await this.userRepository.save(updateUser);
  }

  async remove(id: string) {
    const existUser = await this.findOne(id);

    if (!existUser) {
      throw new HttpException(`id为${id}的用户不存在`, HttpStatus.BAD_REQUEST);
    }
    await this.userRepository.delete(id);
  }
}
